package com.example.springcloudresourceserver.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
public class ResController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/res")
    public ResponseEntity<String> res(){
        return new ResponseEntity<>("<h1>这是资源服务器1受保护的资源</h1>", HttpStatus.OK);
    }

    @GetMapping(value = "/res2/res")
    public ResponseEntity<String> remoteRes(HttpServletRequest request){
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization",request.getHeader("Authorization"));
        System.err.println(JSONObject.toJSONString(headers,true));
        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<String> result = restTemplate.exchange("http://localhost:8080/res",HttpMethod.GET,entity,String.class);
        System.err.println(JSONObject.toJSONString(result,true));
        return result;
    }

    @GetMapping(value = "/res2/getPrincipal",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<OAuth2Authentication> getPrincipal(OAuth2Authentication oAuth2Authentication, Principal principal, Authentication authentication){
        System.err.println(JSONObject.toJSONString(oAuth2Authentication.getUserAuthentication().getAuthorities(),true));
        System.err.println(JSONObject.toJSONString(oAuth2Authentication,true));
        System.err.println(JSONObject.toJSONString(principal,true));
        System.err.println(JSONObject.toJSONString(authentication.getAuthorities(),true));
        return new ResponseEntity<>(oAuth2Authentication,HttpStatus.OK);
    }
}
